package cn.ersan.boot.sms.service;

import cn.ersan.boot.sms.config.AwsMessageConfig;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.MessageAttributeValue;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 86189
 */
@Service
public class SMSService {
    @Resource
    private AwsMessageConfig awsMessageConfig;

    @Value("${aws.sns.phone-number}")
    private String snsPhoneNumber;  // 在 SNS 中注册的电话号码（如果需要）

    private final SnsClient snsClient;

    public SMSService(SnsClient snsClient) {
        this.snsClient = snsClient;
    }

    public String sendSMS(String phoneNumber, String message) {

        Map<String, MessageAttributeValue> smsAttributes =
                new HashMap<>(16);
        //可选
        smsAttributes.put("SenderID", MessageAttributeValue.builder().stringValue(awsMessageConfig.getSenderId()).dataType("String").build());
        //申请的短信发送号码 pipoint服务中
        smsAttributes.put("OriginationNumber", MessageAttributeValue.builder().stringValue(awsMessageConfig.getPromotionalNumber()).dataType("String").build());
        //短信类型
        smsAttributes.put("SMSType", MessageAttributeValue.builder().stringValue("Promotional").dataType("String").build());
        //指定反馈结果
        smsAttributes.put("DeliveryStatusIAMRole", MessageAttributeValue.builder().stringValue(awsMessageConfig.getDeliveryStatusIAMRole()).dataType("String").build());


        // 创建短信请求
        PublishRequest publishRequest = PublishRequest.builder()
                .message(message)
                // 目标手机号
                .phoneNumber(phoneNumber)
                .messageAttributes(smsAttributes)
                .build();

        // 发送短信
        PublishResponse publishResponse = snsClient.publish(publishRequest);
        System.out.println("Message sent with ID: " + publishResponse.messageId());

        return "Message sent successfully to " + phoneNumber;
    }
}
